package com.example.testble;

import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.testble.databinding.ActivityMainBinding;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

//    private GattAuthServer gattAuthServer;

    private static final String TAG = "BluetoothReceiver";

    private void initGattAuthServer() {
        //gattAuthServer = new GattAuthServer(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        BLogger.init(new IVILoggerImpl());

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.toolbar);

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);

        binding.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAnchorView(R.id.fab)
                        .setAction("Action", null).show();
//                gattAuthServer.start();

            }
        });

        this.initGattAuthServer();

        IntentFilter filter111 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();

                if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            BLogger.d(TAG, "Bluetooth is OFF");
                            break;

                        case BluetoothAdapter.STATE_TURNING_OFF:
                            BLogger.d(TAG, "Bluetooth is TURNING OFF");
                            break;

                        case BluetoothAdapter.STATE_ON:
                            BLogger.d(TAG, "Bluetooth is ON");
                            restartGatt();
                            break;

                        case BluetoothAdapter.STATE_TURNING_ON:
                            BLogger.d(TAG, "Bluetooth is TURNING ON");
                            break;
                    }
                }
            }
        }, filter111);

        IntentFilter filter222 = new IntentFilter();
        filter222.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter222.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter222.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter222.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        filter222.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BLogger.d(TAG, "收到广播: " + action);

                if (device != null) {
                    BLogger.d(TAG, "设备: " + device.getAddress());
                }

                if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                    BLogger.d(TAG, "ACL 连接: " + device.getAddress());
                } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                    BLogger.d(TAG, "ACL 断开: " + device.getAddress());
//                    restartGatt();
                } else if (BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                    int state = intent.getIntExtra(BluetoothA2dp.EXTRA_STATE, -1);
                    if (state == BluetoothA2dp.STATE_CONNECTED) {
                        BLogger.d(TAG, "A2DP 连接: " + device.getAddress());
                    } else if (state == BluetoothA2dp.STATE_DISCONNECTED) {
                        BLogger.d(TAG, "A2DP 断开: " + device.getAddress());
                    }
                } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                    int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1);
                    if (state == BluetoothHeadset.STATE_CONNECTED) {
                        BLogger.d(TAG, "HFP 连接: " + device.getAddress());
                    } else if (state == BluetoothHeadset.STATE_DISCONNECTED) {
                        BLogger.d(TAG, "HFP 断开: " + device.getAddress());
                    }
                }
            }
        }, filter222, Context.RECEIVER_EXPORTED);


        UdpBroadcastClient.getInstance().startListening();
        BleGattClient.getInstance();

    }

    private void restartGatt() {
//        gattAuthServer.stop();
//        initGattAuthServer();
//        gattAuthServer.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}